//1.导入模块
import http from 'wechat-http'
//2.配置及地址
http.baseURL = 'https://live-api.itheima.net'
http.timeout = 5000

//配置请求拦截器
http.intercept.request = (params) => {
  //获取token
  const token = getApp().token
  //判断是否有token
  if (token) {
    params.header = {
      //给请求头添加Authorization
      Authorization: `Bearer ${token}`,
      ...params.header
    }
  }
  // 这里必须要有返回
  return params
}
//3.配置响应拦截器
http.intercept.response = async (res) => {
  console.log('拦截器', res);
  if (res.data.code === 401) {
    //如果访问的是/refreshToken
    if (res.config.url.includes('/refreshToken')) {
      //提示用户重新登录
      wx.utils.toast('请重新登录')
      //跳转到登录页
      //页面栈 访问的路径 数组 数组的最后一个元素是当前访问页面
      const currentPages = getCurrentPages()
      // console.log(currents);
      // 获取最后一个页面的路径
      const lastcurrents = currentPages[currentPages.length - 1].route
      // console.log(lastcurrents, 123);
      // 跳转到登录页面 并且携带参数
      return wx.redirectTo({
        url: '/pages/login/index?redirect=' + lastcurrents,
      })
    }
    //代表token过期
    const app = getApp()
    const res2 = await http({
      url: '/refreshToken',
      method: 'post',
      header: {
        Authorization: `Bearer ${app.r_token}`
      }
    })
    console.log(res2);
    app.setToken(res2.data.token, res2.data.refreshToken)
    //处理请求头
    res.config.header = {
      Authorization: `Bearer ${wx.getStorageSync('token')}`
    }
    //调用http方法
    return http(res.config)
  }
  //处理业务失败
  else if (res.data.code !== 10000) {
    wx.showToast({
      title: res.data.message,
      mask: true,
      icon: 'error'
    })
  }
  // 过滤接口返回的数据
  return res.data
};

wx.http = http
export default http